package com.ilink.groundservice.service.impl.AiX;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ilink.groundservice.entity.PO.AiX.AiXResult;
import com.ilink.groundservice.entity.VO.AiX.AiXResultResponse;
import com.ilink.groundservice.mapper.AiX.AiXResultMapper;
import com.ilink.groundservice.service.AiX.AiXResultService;
import com.ilink.ilinkapi.dto.ground.AiX.AiXAreaFilterRequest;
import com.ilink.ilinkapi.dto.ground.AiX.AiXResultInsertRequest;
import com.ilink.ilinkapi.dto.ground.AiX.AiXResultUpdateRequest;
import com.ilink.ilinkcommon.domain.R;
import com.ilink.ilinkcommon.service.oss.MinioService;
import com.ilink.ilinkcommon.utils.SnowflakeIdGenerator;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
@RequiredArgsConstructor
public class AiXResultServiceImpl implements AiXResultService {

  private final AiXResultMapper aiXResultMapper;
  private final MinioService minioService;

  @Override
  public IPage<AiXResultResponse> getResults(AiXAreaFilterRequest request) {
    Page<AiXResult> page = new Page<>(request.getPage(), request.getSize());
    LambdaQueryWrapper<AiXResult> queryWrapper = new LambdaQueryWrapper<>();
    queryWrapper.eq(request.getAreaId() != null, AiXResult::getAreaId, request.getAreaId());

    IPage<AiXResult> resultPage = aiXResultMapper.selectPage(page, queryWrapper);
    List<AiXResultResponse> responseList = resultPage.getRecords().stream().map(result -> {
      AiXResultResponse response = new AiXResultResponse();
      response.setResultId(result.getResultId());
      response.setCoverUrl(result.getCoverUrl());
      response.setResultTitle(result.getResultTitle());
      response.setIntroduction(result.getIntroduction());
      response.setAreaId(result.getAreaId());
      String imagePath = minioService.getBucketFileUrl("dataset-square-migrate", result.getCoverUrl());
      response.setCoverUrl(imagePath != null ? imagePath : "");
      return response;
    }).collect(Collectors.toList());

    Page<AiXResultResponse> responsePage = new Page<>(resultPage.getCurrent(), resultPage.getSize(), resultPage.getTotal());
    responsePage.setRecords(responseList);

    return responsePage;
  }

  @Override
  @Transactional
  public R insertResult(AiXResultInsertRequest request) {
    SnowflakeIdGenerator idGenerator = new SnowflakeIdGenerator(1, 1);
    Long resultId = idGenerator.nextId();

    AiXResult result = new AiXResult();
    result.setResultId(resultId);
    result.setResultTitle(request.getResultTitle());
    result.setIntroduction(request.getIntroduction());
    result.setAreaId(request.getAreaId());

    String objectName = "area/" + request.getAreaId() + "/result/" + resultId + getFileExtension(request.getCoverImage().getOriginalFilename());
    boolean isUploaded = minioService.uploadBucketFile(request.getCoverImage(), "dataset-square-migrate", objectName);
    if (!isUploaded) {
      return R.error("结果封面上传失败");
    }
    result.setCoverUrl(objectName);

    aiXResultMapper.insert(result);
    return R.ok("结果插入成功");
  }

  @Override
  @Transactional
  public R updateResult(AiXResultUpdateRequest request) {
    AiXResult result = new AiXResult();
    result.setResultId(request.getResultId());
    result.setResultTitle(request.getResultTitle());
    result.setIntroduction(request.getIntroduction());
    result.setAreaId(request.getAreaId());

    aiXResultMapper.updateById(result);
    return R.ok("结果更新成功");
  }

  @Override
  @Transactional
  public R updateResultCover(MultipartFile file, Long resultId, Long areaId) {
    String objectName = "area/" + areaId + "/result/" + resultId + getFileExtension(file.getOriginalFilename());
    boolean isUploaded = minioService.uploadBucketFile(file, "dataset-square-migrate", objectName);
    if (!isUploaded) {
      return R.error("结果封面上传失败");
    }

    AiXResult result = aiXResultMapper.selectById(resultId);
    if (result == null) {
      return R.error("结果未找到");
    }

    result.setCoverUrl(objectName);
    aiXResultMapper.updateById(result);
    return R.ok("结果封面更新成功");
  }

  @Override
  @Transactional
  public void deleteResult(Long resultId) {
    AiXResult result = aiXResultMapper.selectById(resultId);
    if (result != null) {
      String coverUrl = result.getCoverUrl();
      int lastSlashIndex = coverUrl.lastIndexOf('/');
      String directory = coverUrl.substring(0, lastSlashIndex + 1);
      String fileName = coverUrl.substring(lastSlashIndex + 1);
      minioService.deleteBucketFile("dataset-square-migrate", directory, fileName);
    }
    aiXResultMapper.deleteById(resultId);
  }

  @Override
  public AiXResultResponse getResult(Long resultId) {
    AiXResult result = aiXResultMapper.selectById(resultId);
    if (result == null) {
      return null;
    }

    AiXResultResponse response = new AiXResultResponse();
    response.setResultId(result.getResultId());
    response.setCoverUrl(result.getCoverUrl());
    response.setResultTitle(result.getResultTitle());
    response.setIntroduction(result.getIntroduction());
    response.setAreaId(result.getAreaId());
    return response;
  }

  private String getFileExtension(String fileName) {
    if (fileName == null) {
      return "";
    }
    int dotIndex = fileName.lastIndexOf('.');
    return dotIndex == -1 ? "" : fileName.substring(dotIndex);
  }
}
